<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<HEAD>
  <style>
     /*#message_list { border: 1px solid black; margin:0px; padding:0px;}*/
     #message-list DIV SPAN { border: 1px solid black;  width: 100px; display:inline-block; margin:0px; padding:1px; }
  </style>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <script src="./_n_o_t_i_f_y_/messenger/json2.js"></script>
  <script>

comet = null;

function onload()
{
  try
  {
  comet = comet_class( "/_n_o_t_i_f_y_/json_rpc" );
  /*alert('onload:' + JSON.stringify( {"X":12}) );
  comet.post( 
    //'{"jsonrpc": "2.0", "method":"open_subscription", "params": { "channels":[{"channel":"test.channel1"}] }, "id":1}',
    comet.createNotify("open_subscription", { channels:[{channel:"test.channel1"}] } ),
    function(){alert('ready');}
  );
   * */
  comet.subscription.channels.push( { channel:"test.channel1"});
  comet.open();
  alert('onload2');
  }
  catch(e)
  {
    alert(e.message);
  }
}

// класс
function comet_class( url )
{

  this.open = function( )
  {
    alert(1);
    if (!this.subscription)
      return;
    if (!this.subscription.channels)
      return;
    this.post(
      this.createNotify("open_subscription", this.subscription),
      function(result)
      {
        alert('yo');
        res = eval('('+result+')');
        alert(res.params);
        comet.uuid = res.params;
        comet.subscribe();
      }
    );
    alert(2);
  }
  
  this.subscribe = function( )
  {
    alert("this.subscribe");
    if ( !this.uuid)
      return;
    alert("subscribe uuid ok!");
    this.post(
      this.createNotify("subscribe", {uuid:this.uuid}),
      function(result)
      {
        alert('yo2');
        res = eval('('+result+')');
        // {"jsonrpc":"2.0","method":"subscribe","params":{"order":0,"limit":0,"lifetime":86400,"channel":"test.channel1","content":"content6"}}
        alert(res.params.content);
        comet.subscribe();
      }
      
    );
  }


  this.post = function( data, callback )
  {
    alert("post:"+ data);
    this.comet1.abort();
    this.comet1.open("POST", this.url, true);
    this.comet1.callback = callback;
    this.comet1.onreadystatechange = 
        function(param)
        {
          //alert(this.readyState);
          if (this.readyState == 4) 
          {
            response = this.responseText;
            alert(response);
            if ( this.callback )
              this.callback(response);
            /*if ( response)
            {
            }*/
          }
        }
    this.comet1.send(data);
  }

/** private*/
  this.createNotify = function(method_name, param_data)
  {
    return JSON.stringify( 
      {
        jsonrpc:"2.0",
        method: method_name,
        params: param_data
      }
    );
    /*
    alert('onload:' + JSON.stringify( {"X":12}) );
    comet.post( '{"jsonrpc": "2.0", "method":"open_subscription", "params": { "channels":[{"channel":"test.channel1"}] }, "id":1}',
     * */

  }
  this.construct=function ()
  {
    var xmlHttp = false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
        try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
         catch (e) {
           try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
           catch (e2) { xmlHttp = false;}
         }
       @end @*/
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); }
    this.comet1 = xmlHttp;
  }

  this.subscription = {};
  this.subscription.channels = [];
  this.url = url;
  this.construct();

  return this;
}




  </script>
</HEAD>
<BODY onload = "javascript:onload()">
<BODY>
</HTML>

      <[!CDATA[


    var anketa_id = 1000000;
    var anketa_id_whom = 2000000;
    var count = -1;
    var update_id = -1;
    var message_counter_self = 1;
    var message_counter_whom = 1;

    var xmlHttp = createHttpRequest();
    var xmlHttpSender = createHttpRequest();

    /* Создание нового объекта XMLHttpRequest для общения с Web-сервером */
    function createHttpRequest()
    {
      var xmlHttp = false;
      /*@cc_on @*/
      /*@if (@_jscript_version >= 5)
         try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
         catch (e) {
           try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
           catch (e2) { xmlHttp = false;}
         }
       @end @*/
      if (!xmlHttp && typeof XMLHttpRequest != 'undefined') { xmlHttp = new XMLHttpRequest(); }
      return xmlHttp;
    }

    function get_value(id) { return 1*document.getElementById(id).innerHTML };
    function set_value(id, v) { document.getElementById(id).innerHTML = v };
    function inc_value(id) { set_value(id, get_value(id) + 1);};

    function get_anketa_id_self() { return document.getElementById("anketa_id_self").value; }
    function get_anketa_id_whom() { return document.getElementById("anketa_id_whom").value; }

    function update_value()
    {
       document.getElementById("anketa_id_self").value = anketa_id;
       document.getElementById("anketa_id_whom").value = anketa_id_whom;
    }

    

    function make_message(text, rev)
    {
      message_counter_self = document.getElementById("id").value;
      message_counter_whom = document.getElementById("id_to").value;
      if ( !rev )
      {
        ++message_counter_self;
        ++message_counter_whom;
      }
      document.getElementById("id").value = message_counter_self;
      document.getElementById("id_to").value = message_counter_whom;

      return "{\"jsonrpc\":\"2.0\",\"method\":\"message\",\"params\":{"
        + '"anketa_id":' + (!rev ?  get_anketa_id_self() :  get_anketa_id_whom())
        + ",\"content\":{ \"anketa_id_from\":" + get_anketa_id_self()
        + ",\"anketa_id_to\":" + get_anketa_id_whom()
        + ",\"id\":" + ( !rev ? message_counter_self : message_counter_whom)
        + ",\"id_to\":" + ( !rev ? message_counter_whom : message_counter_self)
        + ",\"message\":\"" + text + '"'
        + ',"mode":' + (rev ? '"Read"' : '"Unread"')
        + ",\"update_id\":" + update_id +"}}}";
    }

    function make_subscribe_message()
    {
      return "{\"jsonrpc\":\"2.0\",\"method\":\"subscribe\",\"params\":{\"mode\":\"messages_only\",\"anketa_id\":" 
             + get_anketa_id_self() +",\"anketa_id_whom\":"
             + get_anketa_id_whom() +",\"update_id\":"
             + update_id +
             ", \"key\":\"" + document.getElementById("sid").value + "\"" + 
             "}}";
    }

    function make_messages_read_message()
    {
      return "{\"jsonrpc\":\"2.0\",\"method\":\"messages_read\",\"params\":{\"anketa_id\":"
             + get_anketa_id_self() + ",\"anketa_id_whom\":"
             + get_anketa_id_whom() + "}}";
    }


    function send_subscribe_message()
    {
      var c = document.getElementById("subscribe_count").innerHTML;
      c = 1*c + 1;
      document.getElementById("subscribe_count").innerHTML = c;

      var url = "/_n_o_t_i_f_y_/json_rpc";
      xmlHttp.open("POST", url, true);
      xmlHttp.onreadystatechange = server_response;
      var data = make_subscribe_message();
      document.getElementById("status").innerHTML = "wait";
      xmlHttp.send(data );
    }

    function make_set_sid_message()
    {
       var message = "{\"jsonrpc\":\"2.0\",\"method\":\"set_sid\",\"params\":{\"anketa_id\":"
       message += get_anketa_id_self();
       message += ",\"key\":\"";
       message += document.getElementById("sid").value;
       message += "\"}}";
       return message;
    }


    function send_message(text)
    {
      xmlHttpSender.open("POST", "/_n_o_t_i_f_y_/json_rpc", true);
      xmlHttpSender.send( make_message(text, false) + make_message(text, true) );
      inc_value("message-send");

      /*var c = document.getElementById("send_count_all").innerHTML;
      c = 1*c + 1;
      document.getElementById("send_count_all").innerHTML = c;*/
    }

    function send_messages_read()
    {
      var data = make_messages_read_message();
      xmlHttpSender.open("POST", "/_n_o_t_i_f_y_/json_rpc", true);
      xmlHttpSender.send(data);
      inc_value("messages_read-send");
    }


    function send_sid()
    {
      var data = make_set_sid_message();
      xmlHttpSender.open("POST", "/_n_o_t_i_f_y_/json_rpc", true);
      xmlHttpSender.send(data);
    }

    function onpresssid()
    {
      send_sid();
    }

    function on_messages_read()
    {
      send_messages_read();
    }

    function onsend()
    {
      var v = document.getElementById("message").value;
      send_message( v );
      document.getElementById("message").value = 1*v + 1;
    }

    function onsubscribe(v)
    {
       if (/* document.getElementById("subscribe").value*/v == "subscribe" )
       {
         document.getElementById("subscribe").value = "describe";
         send_subscribe_message();
       }
       else
       {
         document.getElementById("subscribe").value = "subscribe";
         xmlHttp.abort();
       }
    }

    var generator = 0;
    function ongenerate(v)
    {
      if ( v == "generate" )
      {
        document.getElementById("generate_button").value = "stop";
        var timeout = document.getElementById("generate_timeout").value;
        generator = setInterval( function(){onsend();}, 1*timeout );
      }
      else
      {
        document.getElementById("generate_button").value = "generate";
        clearInterval(generator);
      }
    }

    function onload()
    {
      uri = new String(window.location);
      pos = uri.indexOf('?');
      if( pos!=-1 )
      {
        pstr = uri.substr(pos + 1, uri.length - pos);
        params = pstr.split('&');
        for ( i in params )
        {
          pair = params[i].split('=');
          if ( pair.length == 2 )
          {
            switch ( pair[0] )
            {
              case "anketa_id": anketa_id = pair[1]; break;
              case "anketa_id_whom": anketa_id_whom = pair[1]; break;
              case "count": count = pair[1]; break;
              case "update-id": update_id = pair[1]; break;
            }
          }
        }
      }

      update_value();

      setTimeout( function() { send_sid(); send_subscribe_message(); }, 100);

      document.getElementById("message-list").innerHTML = "<div><span>id</span><span>id_to</span><span>anketa_id_from</span>" 
                                                        + "<span>anketa_id_to</span><span>mode</span><span>text</span></div>";
    }

    function update_readed(anketa_id)
    {
      tbl = document.getElementById("message-list");
      for ( i=1; i < tbl.childNodes.length; ++i )
      {
        if ( tbl.childNodes[i].childNodes[3].innerHTML == anketa_id)
          tbl.childNodes[i].childNodes[4].innerHTML = "Read";
      }
    }

    function update_message(m)
    {
      elem = document.getElementById("message-"+m.id);
      row = "<span>"+m.id+"</span>"+
        "<span>"+m.id_to+"</span>"+
        "<span>"+m.anketa_id_from+"</span>"+
        "<span>"+m.anketa_id_to+"</span>"+
        "<span>"+m.mode+"</span>"+
        "<span>"+m.message+"</span>" +
        "<span>"+update_id+"</span>";
      tr = document.createElement("DIV");
      tr.id = "message-"+m.id;
      tr.innerHTML = row;
      tbl = document.getElementById("message-list");

      if ( elem )
        tbl.replaceChild(tr, elem);
      else
        tbl.appendChild(tr);
      while ( tbl.childNodes.length > 11 )
        tbl.removeChild(tbl.childNodes[1]);
    }


    function server_response()
    {
      var response = "none";
      try {

      if (xmlHttp.readyState == 4) 
      {
        document.getElementById("status").innerHTML = "ready";
        response = xmlHttp.responseText;
        if ( response)
        {
          /*var c = document.getElementById("receive-count-all").innerHTML;
          c = 1*c + 1;
          document.getElementById("receive-count-all").innerHTML = c;
          */

          var obj = eval( "("+response+")");

          if (obj && obj.params)
          {
            

            if ( document.getElementById("update-id") )
              document.getElementById("update-id").innerHTML = update_id;

            if ( obj.method=="message")
            {
              update_id = obj.params.update_id;
              update_message(obj.params.content);
              /*if ( document.getElementById("receive-count") )
                document.getElementById("receive-count").innerHTML = 1;*/
              inc_value("message-recv");
              send_messages_read();
            }
            else if ( obj.method=="message_list")
            {
              update_id = obj.params.update_id;
              for ( i in obj.params.content.messages)
                update_message(obj.params.content.messages[i]);
              /*if ( document.getElementById("receive-count") )
                document.getElementById("receive-count").innerHTML = obj.params.content.messages.length;*/
              inc_value("message_list-recv");
              set_value("ml-cur", obj.params.content.messages.length);
              if ( get_value("ml-cur") > get_value("ml-max") )
                set_value("ml-max", get_value("ml-cur") );
              send_messages_read();
            }
            else if ( obj.method=="messages_read")
            {
              update_id = obj.params.update_id;
              inc_value("messages_read-recv");
              update_readed(obj.params.anketa_id_whom);
            }
            else if ( obj.method=="auth_error")
              document.getElementById("status").innerHTML = "error";
              //alert( obj.method );
          }
        }

        if ( document.getElementById("subscribe").value == "describe")
        {
          if ( obj.method!="auth_error" ) 
            send_subscribe_message();
          else
            onsubscribe("describe");
        }
      }

      } catch(e) { /*alert("server_response: " + e.message + ": " + response );*/}
    }

    if (document.addEventListener) 
    {
      document.addEventListener("DOMContentLoaded", onload, false);
    }

  </script>
</HEAD>
<BODY onload = "javascript:onload()">
<H1> Messenger 2</H1>
<div>
  <div> Статус подписки <span id="status">undef</span> ( отправлено <span id="subscribe_count">0</span> ) </div>
  <div> Текущий update_id <span id="update-id">0</span> </div>
  <div> Получено message <span id="message-recv">0</span>, отправлено(пар) <span id="message-send">0</span> </div>
  <div> Получено message_list <span id="message_list-recv">0</span> (<span id="ml-cur">0</span>,<span id="ml-max">0</span>) </div>
  <div> Получено messages_read <span id="messages_read-recv">0</span>, отправлено <span id="messages_read-send">0</span> </div>

<!-- 
  <div> receive count <span id="receive-count"/> </div>
  <div> receive count all <span id="receive-count-all">0</span> </div>
  <div> send count all <span id="send_count_all">0</span> </div>
-->

  <!-- <div> subscribe count<span id="subscribe_count">0</span> </div> -->
  <div> anketa_id self <input id = "anketa_id_self" type="text" value="1000000"/> </div>
  <div> anketa_id whom <input id = "anketa_id_whom" type="text" value="2000000"/> </div>

  <div> sid <INPUT id = "sid" type="text" value="0123456789"></INPUT>
            <INPUT type="button" onclick="javascript:onpresssid()" value="send sid"></INPUT>
  </div>
  <input id="subscribe" type="button" value="describe" onclick="javascript:onsubscribe(value)"/>

  <div> 
    <textarea id = "message" name="message" cols="40" rows="3"></textarea>
  </div>
  <input type="button" value="send" onclick="javascript:onsend()"/>
  <input id="generate_timeout" type="text" value="1000"/>
  <input id="generate_button" type="button" value="generate" onclick="javascript:ongenerate(value)"/>
  <div> id <input id = "id" type="text" value="1"/> </div>
  <div> id_to <input id = "id_to" type="text" value="100"/> </div>

  <div>
    <input id="messages_read" type="button" value="messages_read" onclick="javascript:on_messages_read()"/>
    <div id = "message-list">
    </div>
  </div>


</div>

<!-- <DIV>anketa_id: <SPAN id="anketa_id"></SPAN> </DIV>
<DIV>count: <SPAN id="count"></SPAN> </DIV>
<DIV>update_id: <SPAN id="update-id"></SPAN> </DIV>
-->
</BODY>
</HTML>
      
      ]]>